package com.cetc.nsfx.controller;

import cn.apiclub.captcha.Captcha;

import com.cetc.nsfx.service.sys.UserService;
import com.cetc.nsfx.util.EncryptUtils;
import com.cetc.nsfx.util.GlobalKeys;

import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;


/**
 * Created by Administrator on 2015/12/24 0024.
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    public static final Log logger = LogFactory.getLog(LoginController.class.getName());

    @Autowired
    UserService userService;

    @RequestMapping(params = "login")
    public String toLogin(){
        return "login";
    }

    @RequestMapping(params = "main")
    public ModelAndView login(HttpSession session, HttpServletRequest req) {

        ModelAndView modelView = new ModelAndView();
        Subject currentUser = SecurityUtils.getSubject();
        modelView.addObject("loginError", true);
        modelView.addObject("errorMsg", "无权访问");
        modelView.setViewName("/login");
        try{
            if(!currentUser.isAuthenticated()){
                String username = req.getParameter("username");
                String password = req.getParameter("password");

                String captcha = req.getParameter(GlobalKeys.VALIDATE_CODE_NAME);
                Captcha sessionCaptcha = (Captcha) req.getSession().getAttribute(GlobalKeys.SESSION_CAPTCHA);
                if(!sessionCaptcha.isCorrect(captcha)){
                    modelView.addObject("loginError", true);
                    modelView.addObject("errorMsg", "验证码错误");
                    modelView.setViewName("/login");
                    return modelView;
                }

                UsernamePasswordToken token = new UsernamePasswordToken(
                        username, password);
                //token.setRememberMe(true);
                currentUser.login(token);

                if(currentUser.isAuthenticated()){
                    Map<String,Object> user = userService.getUserByUserId(username);
                    session.setAttribute("userinfo", user);
                    return new ModelAndView("redirect:/home/main.do");
                }
            }
        }catch(Exception e){
            currentUser.logout();
            modelView.addObject("loginError", true);
            modelView.addObject("errorMsg", e.getMessage());

            return modelView;
        }
        currentUser.logout();
        return modelView;
    }

    @RequestMapping("/login2")
    public String login2(HttpServletRequest req, HttpServletResponse resp){

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter(GlobalKeys.VALIDATE_CODE_NAME);

        Captcha sessionCaptcha = (Captcha) req.getSession().getAttribute(GlobalKeys.SESSION_CAPTCHA);
        if(!sessionCaptcha.isCorrect(captcha)){
            req.setAttribute("captchaError",1);
            return "login";
        }

       Map<String,Object> user = userService.getUserByUserIdPassword(username,password);
        if (user == null){
            req.setAttribute("userError",1);
            return "login";
        }

        System.out.println("login success");
        return "redirect:/main/index";

    }

    @RequestMapping(params = "/logout")
    public ModelAndView logout(HttpSession session, HttpServletRequest req) {
    	  ModelAndView modelView = new ModelAndView();
    	  modelView.setViewName("/login");
    	  Subject currentUser = SecurityUtils.getSubject();
    	  currentUser.logout();
    	  return modelView;
    	  
    }
    
    
    /*protected UserContext getUserContext(){
        Subject currentUser = SecurityUtils.getSubject();
        return (UserContext)currentUser.getPrincipal();
    }*/
}
